package com.zgm.ch04.beanPostProcessor._8_1;

import java.lang.reflect.Field;
import java.util.Date;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;


public class TimestampingBeanPostProcessor implements BeanPostProcessor {

	public Object postProcessAfterInitialization(final Object bean, String beanName)
			throws BeansException {
		
		ReflectionUtils.doWithFields(bean.getClass(), 
		   new ReflectionUtils.FieldCallback(){

				public void doWith(Field field) throws IllegalArgumentException,
						IllegalAccessException {
					field.set(bean, new Date());
				}
				
		}, new ReflectionUtils.FieldFilter(){

				public boolean matches(Field field) {
					return field.getType() == Date.class && field.getAnnotation(Timestamp.class) != null;
				}
				
		});
		
		return bean;
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	
}
